package kr.hkit.androidcomplete03.ch281;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch281.common.Item;
import kr.hkit.androidcomplete03.ch281.common.MyAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class DomParser extends Activity {
	ListView list;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch281_parser);
		list = (ListView) findViewById(R.id.ch281_parser_listview);
		
		new ParsingXml().execute("order.xml");
	}
	
	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>>{
		ProgressDialog progressDlg;
		@Override
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(DomParser.this, "Wait", "Xml Parsing. . . ");
	
		}
		
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str =  null;
			BufferedReader br = null;
			try {
				br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str = br.readLine()) != null){
					sb.append(str);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					br.close();} catch (IOException e) {	e.printStackTrace();}
			}
			return parsingXml(sb.toString());
		}
		
		private ArrayList<Item> parsingXml(String xml) {
			Log.d("XML Parsing", xml);
			ArrayList<Item> itemLists = new ArrayList<Item>();
			Item item;
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			try {
				
				DocumentBuilder builder = factory.newDocumentBuilder();
				InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
				Document doc = builder.parse(is);
				
				Element order = doc.getDocumentElement(); //find out <order>
				NodeList items = order.getElementsByTagName("item");
				
				//<order> 하위 item 태그노드 읽음
				for(int i =0; i < items.getLength(); i++){
					Item itemForRead = new Item();
					Node node = items.item(i);
					
					// 마우스 태그 줄 읽음 //<item Price="23000" Maker="Samsung">Mouse</item>
					Node childNode = node.getFirstChild(); // mouse node
					itemForRead.setItemName(childNode.getNodeValue()); // "Mouse"
				
					NamedNodeMap attrs = node.getAttributes();
					// <item Price="23000" Maker="Samsung"> 속성 순회
					for(int j =0; j<attrs.getLength(); j++){
						Node attr = attrs.item(j); // //Price="2300" or Maker="Samsung"
						
						 if(attr.getNodeName().equalsIgnoreCase("price")){//대소문자 무시
							 itemForRead.setItemPrice(Integer.parseInt(attr.getNodeValue()));
						 }else{
							 itemForRead.setItemMaker(attr.getNodeValue());
						 }
					}
					itemLists.add(itemForRead);
				}
				
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return itemLists;
		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			progressDlg.dismiss();
			MyAdapter adapter = new MyAdapter(getApplicationContext(), result);
			list.setAdapter(adapter);
		}
	}
}
